package com.ysuedu.dao;

import com.ysuedu.common.DBUtils;
import com.ysuedu.entity.BookCategory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BookDao {
    //查询指定类别下所有子类，返回null说明没有子类
  List<BookCategory> findAllChild(String cate){
      List<BookCategory> childCategorys=new ArrayList<BookCategory>();
      System.out.println("开始程序");
      String sql="SELECT * FROM bookcategory WHERE category=?";
      String sql2="select * from bookcategory where categoryId=?";
      try{
          Connection connection=DBUtils.getConnection();
          PreparedStatement ps= connection.prepareStatement(sql);
          ps.setString(1,"科技");
          ResultSet rs=ps.executeQuery();
          if(rs.next()){
              String children=rs.getString("childId");
              List<String> childId= Arrays.asList(children.split(","));
              for(String id:childId){
                  ps=DBUtils.getPreparedStatement(sql2);
                  ps.setInt(1,Integer.parseInt(id));
                  rs=ps.executeQuery();
                  if(rs.next()){
                      BookCategory bc=new BookCategory();
                      bc.setCategory(rs.getString("category"));
                      bc.setCategoryId(rs.getInt("categoryId"));
                      bc.setParentId(rs.getString("parentId"));
                      bc.setChildId(rs.getString("childId"));
                      bc.setLevel(rs.getInt("level"));
                      childCategorys.add(bc);
                  }
              }
              DBUtils.close(connection,ps,rs);
              return childCategorys;
          }

      }catch (Exception e){
          e.getStackTrace();
          return null;
      }
    return null;
  }


  public static void main(String[] args){
//      BookDao dao=new BookDao();
//      List<BookCategory> list=dao.findAllChild("科技");
//      if(list==null)System.out.println("未找到");
//      else{
//          for (BookCategory bc:list){
//              System.out.println(bc.getCategory());
//          }
//      }
//      String sql="select * from bookcategory where category=?";
//      try{
//          Connection connection=DBUtils.getConnection();
//          PreparedStatement ps=connection.prepareStatement(sql);
//          ps.setString(1,"科技");
//          ResultSet rs=ps.executeQuery();
//          if(rs.next()){
//              System.out.println(rs.getInt("categoryId"));
//
//          }
//      }catch (Exception e){
//          e.getStackTrace();
//      }
        BookDao dao=new BookDao();
        List<BookCategory> c=dao.findAllChild("科技");
        for(BookCategory cate:c){
            System.out.println(cate.getCategory());
        }

  }
}
